package top.drinyeit.nongmao.viewmodel;

import android.content.Intent;
import android.databinding.ObservableBoolean;
import android.databinding.ObservableField;
import android.databinding.ObservableInt;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.scu.miomin.shswiperefresh.core.SHSwipeRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import top.drinyeit.nongmao.activity.ConfirmOrderActivity;
import top.drinyeit.nongmao.adapter.CartAdapter;
import top.drinyeit.nongmao.app.Constant;
import top.drinyeit.nongmao.app.MyApplication;
import top.drinyeit.nongmao.common.ItemClick;
import top.drinyeit.nongmao.dialog.LoadDialog;
import top.drinyeit.nongmao.fragment.CartFragment;
import top.drinyeit.nongmao.model.CartBean;
import top.drinyeit.nongmao.model.CartListBean;
import top.drinyeit.nongmao.model.TemporaryOrderDetailBean;
import top.drinyeit.nongmao.model.param.CartParam;
import top.drinyeit.nongmao.retrofit.HttpResponse;
import top.drinyeit.nongmao.retrofit.RetrofitMethod;
import top.drinyeit.nongmao.retrofit.subscriber.CommonSubscriber;
import top.drinyeit.nongmao.retrofit.subscriber.SubscriberListener;
import top.drinyeit.nongmao.util.SPUtil;
import top.drinyeit.nongmao.util.StringUtil;

import static top.drinyeit.nongmao.app.Constant.COMMON_SUCCESS;

/**
 * Created by YJY on 2018/1/10.
 */

public class CartVM {

    public static ObservableInt cartCheckedNumber = new ObservableInt(0);
    public static ObservableField<String> cartPrice = new ObservableField<>("0");
    public static ObservableBoolean allChecked = new ObservableBoolean(false);
    public ObservableBoolean editMode = new ObservableBoolean(false);

    private CartFragment fragment;
    public static CartAdapter cartAdapter;

    public CartVM(final CartFragment fragment) {
        this.fragment = fragment;
        if (cartPrice == null) {
            cartPrice = new ObservableField<>("0");
        }
        if (cartCheckedNumber == null) {
            cartCheckedNumber = new ObservableInt(0);
        }
        if (allChecked == null) {
            allChecked = new ObservableBoolean(false);
        }
        initRefreshLayout();
        getCartList();
    }

    private void initRefreshLayout() {
        fragment.shSwipeRefreshLayout.setLoadmoreEnable(false);
        fragment.shSwipeRefreshLayout.setOnRefreshListener(new SHSwipeRefreshLayout.SHSOnRefreshListener() {
            @Override
            public void onRefresh() {
                getCartList();
            }

            @Override
            public void onLoading() {
            }

            @Override
            public void onRefreshPulStateChange(float v, int i) {

            }

            @Override
            public void onLoadmorePullStateChange(float v, int i) {

            }
        });
    }

    public void getCartList() {
        String user_id = SPUtil.getShareString(Constant.USER_ID);
        if (user_id.equals("")) {
            Toast.makeText(MyApplication.getInstance(), "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }
        CommonSubscriber<HttpResponse<CartListBean>> subscriber = new CommonSubscriber<>(new SubscriberListener<HttpResponse<CartListBean>>() {
            @Override
            public void onError(String e, int code) {
                fragment.shSwipeRefreshLayout.finishRefresh();
                Toast.makeText(MyApplication.getInstance(), "获取购物车列表失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(HttpResponse<CartListBean> o) {
                fragment.shSwipeRefreshLayout.finishRefresh();
                if (o.getData() != null) {
                    SetCartData(o.getData().getShopping_cart_list());
                } else if (o.getData() == null || o.getData().getShopping_cart_list().size() == 0) {
                    if (cartAdapter != null) {
                        cartAdapter.clear();
                        cartAdapter.notifyDataSetChanged();
                        calculatePriceAndNumber();
                    } else {
                        calculatePriceAndNumber();
                    }
                }
            }
        });
        RetrofitMethod.getInstance().cartList(subscriber, user_id);
    }

    private void SetCartData(List<CartListBean.CartShopBean> o) {
        List<CartBean> cartData = null;
        try {
            cartData = handleList(o);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        cartPrice.set("0");
        cartCheckedNumber.set(0);
        allChecked.set(false);
        if (cartData != null && cartData.size() > 0) {
            if (cartAdapter == null) {
                cartAdapter = new CartAdapter(fragment.getActivity(), cartData, new ItemClick() {
                    @Override
                    public void onItemClick(View view, int position) {
                        switch (cartAdapter.getItemViewType(position)) {
                            case 1: //点击店铺头
                                // TODO: 2018/1/11 购物车点击店铺头
                                break;
                            case 2: //点击商品
                                // TODO: 2018/1/11 购物车点击商品
                                break;
                            default:
                                break;
                        }
                    }
                });
                fragment.cartList.setAdapter(cartAdapter);
            } else {
                cartAdapter.setData(cartData);
                cartAdapter.notifyDataSetChanged();
            }
        } else {
            if (cartAdapter != null) {
                cartAdapter.clear();
                cartAdapter.notifyDataSetChanged();
            }
        }
    }

    //编辑
    public void edit(View view) {
        if (editMode.get()) {   //编辑完成后重新计算
            calculatePriceAndNumber();
        }
        editMode.set(!editMode.get());
    }

    //去结算
    public void account(final View view) {
        if (cartAdapter == null || cartAdapter.getData() == null) {
            Toast.makeText(view.getContext(), "购物车为空", Toast.LENGTH_SHORT).show();
        }
        if (Double.valueOf(cartPrice.get()) <= 0.0) {
            Toast.makeText(view.getContext(), "您还未选择商品", Toast.LENGTH_SHORT).show();
        } else if (SPUtil.getShareString(Constant.USER_ID).equals("")) {
            Toast.makeText(MyApplication.getInstance(), "请先登录", Toast.LENGTH_SHORT).show();
        } else {
            final LoadDialog loadDialog = new LoadDialog(view.getContext());
//            loadDialog.show();  4.4运行闪退
            List<CartParam.StoreParam> storeParams = new ArrayList<>();
            int position = -1;
            for (CartBean cartBean : cartAdapter.getData()) {
                if (cartBean.getChecked() && cartBean.getType() == 2) {
                    CartParam.StoreParam.GoodsParam goodsParam = new CartParam.StoreParam.GoodsParam(cartBean.getId(), cartBean.getCommodity_sum());
                    if (position == cartBean.getPosition()) {
                        CartParam.StoreParam storeParam = storeParams.get(storeParams.size() - 1);
                        storeParam.getCommodity_list().add(goodsParam);
                    } else {
                        List<CartParam.StoreParam.GoodsParam> goodsParams = new ArrayList<>();
                        goodsParams.add(goodsParam);
                        CartParam.StoreParam storeParam = new CartParam.StoreParam(cartBean.getStore_id(), goodsParams);
                        storeParams.add(storeParam);
                        position = cartBean.getPosition();
                    }
                }
            }
            CartParam cartParam = new CartParam(SPUtil.getShareString(Constant.USER_ID), storeParams);
            CommonSubscriber<HttpResponse<TemporaryOrderDetailBean>> subscriber = new CommonSubscriber<>(new SubscriberListener<HttpResponse<TemporaryOrderDetailBean>>() {
                @Override
                public void onError(String e, int code) {
                    loadDialog.dismiss();
                    Toast.makeText(MyApplication.getInstance(), "下单失败", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onNext(HttpResponse<TemporaryOrderDetailBean> o) {
                    loadDialog.dismiss();
                    if (o.getCode() == COMMON_SUCCESS) {
                        Intent intent = new Intent(fragment.getActivity(), ConfirmOrderActivity.class);
                        intent.putExtra("temp_order", o.getData());
                        fragment.startActivity(intent);
                    } else {
                        Toast.makeText(MyApplication.getInstance(), o.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
            RetrofitMethod.getInstance().cartAccount(subscriber, new Gson().toJson(cartParam));
        }

    }

    //删除
    public void delete(View view) {
        if (cartAdapter == null || cartAdapter.getData().size() == 0) {
            Toast.makeText(MyApplication.getInstance(), "购物车为空", Toast.LENGTH_SHORT).show();
        } else if (cartCheckedNumber.get() <= 0) {
            Toast.makeText(MyApplication.getInstance(), "请选择删除的商品", Toast.LENGTH_SHORT).show();
        } else {
            final List<CartBean> containShopCarts = new ArrayList<>();
            List<CartBean> exceptShopCarts = new ArrayList<>();
            for (CartBean cartBean : cartAdapter.getData()) {
                if (cartBean.getChecked()) {
                    containShopCarts.add(cartBean);
                    if (cartBean.getType() == 2) {
                        exceptShopCarts.add(cartBean);
                    }
                }
            }
            CommonSubscriber<HttpResponse<String>> subscriber = new CommonSubscriber<>(new SubscriberListener<HttpResponse<String>>() {
                @Override
                public void onError(String e, int code) {
                    Toast.makeText(MyApplication.getInstance(), "删除购物车内商品失败", Toast.LENGTH_SHORT).show();
                }

                public void onNext(HttpResponse<String> o) {
                    if (o.getCode() == COMMON_SUCCESS) {
                        allChecked.set(false);
                        removeAndReset(containShopCarts);
                        cartCheckedNumber.set(0);
                        cartPrice.set("0");
                    }
                    Toast.makeText(MyApplication.getInstance(), o.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
            StringBuilder deleteGoodsIds = new StringBuilder();
            for (int i = 0; i < exceptShopCarts.size(); i++) {
                deleteGoodsIds.append(exceptShopCarts.get(i).getId());
                if (i < (exceptShopCarts.size() - 1)) {
                    deleteGoodsIds.append(",");
                }
            }
            RetrofitMethod.getInstance().deleteCart(subscriber, deleteGoodsIds.toString());
        }
    }

    //全选
    public void selectAll(View view) {
        if (cartAdapter != null && cartAdapter.getData().size() > 0) {
            if (!allChecked.get()) {  //全选
                for (CartBean cartBean : cartAdapter.getData()) {
                    cartBean.setChecked(true);
                }
                cartAdapter.notifyDataSetChanged();
                allChecked.set(true);
                calculatePriceAndNumber();
            } else { //取消全选
                for (CartBean cartBean : cartAdapter.getData()) {
                    cartBean.setChecked(false);
                }
                cartAdapter.notifyDataSetChanged();
                allChecked.set(false);
                cartCheckedNumber.set(0);
                cartPrice.set("0");
            }
        }
    }

    private void removeAndReset(List<CartBean> cartList) {
        int i = cartAdapter.getData().indexOf(cartList.get(0));
        int startPosition = cartList.get(0).getPosition();
        if (cartList.get(0).getType() == 1) {
            startPosition--;
        }
        for (CartBean cartBean : cartList) {
            int position = cartAdapter.getData().indexOf(cartBean);
            cartAdapter.getData().remove(cartBean);
            cartAdapter.notifyItemRemoved(position);
        }
        for (int i1 = i; i1 < cartAdapter.getData().size(); i1++) {
            if (cartAdapter.getData().get(i1).getType() == 1) {
                startPosition++;
            }
            cartAdapter.getData().get(i1).setPosition(startPosition);
        }
    }

    public static void calculatePriceAndNumber() {
        if (cartAdapter != null && cartAdapter.getData().size() > 0) {
            int i = 0;
            double j = 0.0;
            for (CartBean cartBean : cartAdapter.getData()) {
                if (cartBean.getChecked() && cartBean.getType() == 2) {
                    i++;
                    j += ((cartBean.getCommodity_price()) * (cartBean.getCommodity_sum()));
                }
            }
            cartCheckedNumber.set(i);
            cartPrice.set(StringUtil.toPrice(j));
        }else {
            int i = 0;
            double j = 0.0;
            cartCheckedNumber.set(i);
            cartPrice.set(StringUtil.toPrice(j));
        }
    }

    private List<CartBean> handleList(List<CartListBean.CartShopBean> list) throws CloneNotSupportedException {
        List<CartBean> temp = new ArrayList<>();
        if (null == list || 0 == list.size()) {
            return temp;
        }
        int total = 0;
        for (int i = 0; i < list.size(); i++) {
            ++total;
            CartBean cartBean = (CartBean) list.get(i).getCommodity_list().get(0).clone();
            cartBean.setType(1);
            cartBean.setStore_name(list.get(i).getStore_name());
            cartBean.setStore_id(list.get(i).getStore_id());
            cartBean.setPosition(i);
            temp.add(cartBean);
            for (int j = 0; j < list.get(i).getCommodity_list().size(); j++) {
                ++total;
                CartBean cartBean1 = list.get(i).getCommodity_list().get(j);
                cartBean1.setType(2);
                cartBean1.setPosition(i);
                cartBean1.setStore_name(list.get(i).getStore_name());
                cartBean1.setStore_id(list.get(i).getStore_id());
                temp.add(cartBean1);
            }
        }
        return temp;
    }

}